<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>文件上传与管理</title>
    <script src="./jquery.min.js"></script>
</head>
<style>
    #box1 {
        min-width: 800px; max-width: 1600px; margin: 20px auto; padding: 60px 40px; border: 2px solid rgb(60,60,60); border-radius: 40px;
    }
    #upgrateBox {
        position: absolute; bottom: 10px; text-align: left; width: 100px; right: 120px;
    }
    .none {
        display: none;
    }
    .name-list {
        display: inline-block; width: 300px;
    }
</style>
<body>
    <div id="box1">
        <form enctype="multipart/form-data" action="upload.php" method="POST">
            <select name="fileType" id="fileType">
                <option value="imgZip">图片压缩包</option>
                <option value="videoZip">视频压缩包</option>
                <option value="emailZip">邮箱图片压缩包</option>
            </select>
            <input type="file" name="file" id="file">
            <button type="button" onclick="uploadChunk()">上传文件</button>
        </form>
        <div>上传进度：<span id="chunkId"></span>%<span></span></div>
        <br/>
        <div>注意：只能上传压缩包文件</div>
        <div>注意：视频压缩包中的文件名不能包含空格，不能使用mov格式的视频(h5网页一般都不能播放)</div>
        <div>注意：压缩包上传完成之后情况点击下列按钮，操作。不能刷新页面，若刷新页面请重新上传</div>
        <div>注意：上传过程中遇到上传失败，请刷新页面重新上传</div>
        <br/>
        <div>
            <span id="targetFile"></span><br/>
            <button type="button" onclick="doUnzip('img')">处理图片</button>
            <button type="button" onclick="doUnzip('video')">处理视频</button>
            <button type="button" onclick="doUnzip('email')">处理邮箱图片</button>
        </div>
        <div>注意：处理过程可能较久，请保持等待(最多30秒)，期间不要刷新页面。直到弹框提示处理完成</div>
    </div>
    <div>
        <button onclick="list('img')">图片资源</button> <button onclick="list('video')">视频列表</button> <button onclick="list('email')">邮箱图片</button>
    </div>
    <div id="list-img" class="none"></div>
    <div id="list-video" class="none"></div>
    <div id="list-email" class="none"></div>
    <div id="upgrateBox">
        <fieldset>系统升级</fieldset>
        <div style="border: 1px solid blue;margin-bottom: 4px;width: 200px;">
            <form enctype="multipart/form-data" id="upgrateForm">
                <input type="file" name="file" id="upgratefile">
            </form>
            <button onclick="upgrate()">升级文件</button>
        </div>
        <div style="border: 1px solid blue;width: 200px;">
            <form enctype="multipart/form-data" id="setting">
                <select name="type" id="settingtype">
                    <option value="img">图片访问地址</option>
                    <option value="video">视频访问地址</option>
                    <option value="email">邮箱图片访问地址</option>
                </select>
                <input type="text" name="host" id="settinghost" value="" placeholder="http/https开头"> 
            </form>
            <button onclick="setHost()">设置</button>
        </div>
    </div>
</body>
</html>
<script>
    let chunkSize = 1024 * 1024; // 1MB 分片尺寸
    let totalChunks = 0;
    let chunkIndex = 0;
    var offset = 0;
    var totalSize = 0;

    $(document).ready(function() {
        $('#file').on('change', function() {
            totalSize = $(this).get(0).files[0].size;
            totalChunks = Math.ceil(totalSize / chunkSize);
            $('#total_chunks').val(totalChunks);
        });
    });

    //设置host配置
    function setHost() {
        let type = $('#settingtype').val();
        let host = $('#settinghost').val();
        console.log(type)
        $.ajax({
            url: 'setting.php',
            type: 'POST',
            data: {
                type: type,
                host: host,
            },
            dataType: 'json',
            success: function(response) {
                console.log(response);
                if (response.code == 1) {
                    alert('设置完成');
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                } else {
                    alert('设置失败 ['+response.msg+']');
                }
            },
            error: function() {
                alert('获取失败');
            }
        });
    }

    function list(type) {
        console.log(type)
        $.ajax({
            url: 'list.php',
            type: 'POST',
            data: {
                listtype: type
            },
            dataType: 'json',
            success: function(response) {
                console.log(response.list);
                let host = response.host;
                let str = '';
                switch (type) {
                    case 'img':
                        for (const key in response.list) {
                            const element = response.list[key];
                            if (element.slice(-3) === 'zip') {

                            } else {
                                str += '<div><span class="name-list">'+element+'</span></div>';
                            }
                        }
                        $('#list-img').html(str);
                        $('#list-img').removeClass('none');
                        $('#list-email').removeClass('none');
                        $('#list-email').addClass('none');
                        $('#list-video').removeClass('none');
                        $('#list-video').addClass('none');
                        break;
                    case 'video':
                        for (const key in response.list) {
                            const element = response.list[key];
                            if (element.slice(-3) === 'zip') {

                            } else {
                                str += '<div><span class="name-list">'+element+'</span><span>访问链接：'+host+element+'</span></div>';
                            }
                        }
                        $('#list-video').html(str);
                        $('#list-video').removeClass('none');
                        $('#list-img').removeClass('none');
                        $('#list-img').addClass('none');
                        $('#list-email').removeClass('none');
                        $('#list-email').addClass('none');
                        break;
                    case 'email':
                        for (const key in response.list) {
                            const element = response.list[key];
                            if (element.slice(-3) === 'zip') {

                            } else {
                                str += '<div><span class="name-list">'+element+'</span><span>访问链接：'+host+element+'</span></div>';
                            }
                        }
                        $('#list-email').html(str);
                        $('#list-email').removeClass('none');
                        $('#list-img').removeClass('none');
                        $('#list-img').addClass('none');
                        $('#list-video').removeClass('none');
                        $('#list-video').addClass('none');
                        break;
                    default:
                        break;
                }
            },
            error: function() {
                alert('获取失败');
            }
        });
    }

    //升级文件
    function upgrate() {
        let formData = new FormData($('#upgrateForm')[0]);
        $.ajax({
            url: 'upgrate.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(response) {
                console.log(response);
                if (response.code == 1) {
                    alert('升级完成');
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                } else {
                    alert('升级失败 ['+response.msg+']');
                }
            },
            error: function() {
                alert('升级失败');
            }
        });
    }

    function doUnzip(typeName) {
        let formData = new FormData();
        formData.append('type', typeName);
        formData.append('targetFile', $('#targetFile').html());
        $.ajax({
            url: 'unzip.php',
            type: 'POST',
            timeout: 5000*6,//超时时间 30秒
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(response) {
                console.log(response);
                if (response.code == 1) {
                    alert('处理完成');
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                } else {
                    alert('处理失败 ['+response.msg+']');
                }
            },
            error: function() {
                alert('处理失败');
            }
        });
    }

    function uploadChunk() {
        var formData = new FormData();
        var tfile = $('#file').get(0).files[0];
        formData.append('file', tfile.slice(offset, offset + chunkSize));
        formData.append('chunk_index', chunkIndex);
        formData.append('total_chunks', totalChunks);
        formData.append('fileType', $('#fileType').val());
        formData.append('fileName', $('#file').get(0).files[0].name);
        console.log(offset, offset + chunkSize);
        chunkIndex++;
        $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(response) {
                console.log(response);
                if (response.code == 1) {
                    if (chunkIndex < totalChunks) {
                        $('#chunkId').html((chunkIndex/totalChunks*100).toFixed(2));
                        offset += chunkSize;
                        uploadChunk();
                    } else {
                        alert('上传完成');
                        $('#chunkId').html(100);
                        console.log(response.filePath);
                        $('#targetFile').html(response.filePath);
                        totalChunks = 0;
                        chunkIndex = 0;
                    }
                } else {
                    alert('上传失败 ['+response.msg+']');
                }
            },
            error: function() {
                alert('上传失败');
            }
        });
    }
</script>